package com.cn.test.xuanhttplibrary.okhttp;

import com.cn.test.xuanhttplibrary.okhttp.builder.GetBuilder;
import com.cn.test.xuanhttplibrary.okhttp.builder.PostBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;

/**
 * @author liuxan
 * @time 2017/3/29 23:36
 * @des
 */

public class HttpUtils {

    public static String TAG = "HTTP";

    private static HttpUtils instance = new HttpUtils();

    private HttpUtils() {
    }

    public static HttpUtils getInstance() {
        return instance;
    }

    private OkHttpClient mOkHttpClient;

    public OkHttpClient getOkHttpClient() {
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        }
        return mOkHttpClient;
    }

    public static PostBuilder post() {
        return new PostBuilder(instance);
    }

    public static GetBuilder get() {
        return new GetBuilder(instance);
    }

    /**
     * add by zxx 20190801
     * activity销毁后，网络请求依然存在，造成内存泄露
     * tag与网络请求关联起来
     * onDestroy 调用
     * @param obj
     */
    public static void canAllByTag(Object obj){
        if(obj != null){
            List<Object> list = mCalls.get(obj);
            if(list != null){
                for (Object one : list) {
                    if(one instanceof GetBuilder.GetCall){
                        GetBuilder.GetCall getCall = (GetBuilder.GetCall) one;
                        if(getCall != null && getCall.getCall() != null){
                            getCall.getCall().cancel();
                        }
                    }
                }
            }
            mCalls.remove(obj);
        }
    }

    public static Map<Object, List<Object>> getCalls(){
        return mCalls;
    }

    private static Map<Object, List<Object>> mCalls = new HashMap<>();
}
